/*
 * Copyright (c) 2019-2029, <a href="https://wwww.intellijboy.cn">https://wwww.intellijboy.cn</a> (liuburu@qq.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * <p>
 * <a href="https://www.apache.org/licenses/LICENSE-2.0">https://www.apache.org/licenses/LICENSE-2.0</a>
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */

package com.github.toucan.demo.stream;

import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Flux;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 流式相应返回控制器
 *
 * @author intellijboy
 * @since 1.0
 */
@Slf4j
@RestController
@RequestMapping("stream/demo")
public class StreamDemoController {

    public static final String[] CN_NICK_NAMES = {"张三", "李四", "王五", "赵六", "小七", "小八", "小九", "小十"};

    @RequestMapping("/hello")
    public Flux<ResponseEntity<String>> hello() {
        // 模拟流式返回，每隔一秒发送一个元素
        AtomicInteger count = new AtomicInteger(0);
        return Flux.generate((sink) -> {
            sleepForWhile();
            if (count.get() == CN_NICK_NAMES.length) {
                sink.next(ResponseEntity.ok(null));
                sink.complete();
            } else {
                // 获取一个随机字符串
                String employ = CN_NICK_NAMES[count.get()];
                log.warn("正在遍生成字符串：{}", employ);
                sink.next(ResponseEntity.ok(employ));
                count.getAndIncrement();
            }
        });
    }

    private void sleepForWhile() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }

}
